<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 欢迎卡片 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card class="welcome-card" shadow="hover">
          <div class="welcome-content">
            <div class="welcome-info">
              <h2>欢迎回来，{{ userStore.name || userStore.username }}</h2>
              <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
              <p>当前角色: {{ userStore.userRole }}</p>
              
              <div class="quick-actions">
                <el-button type="primary" @click="toPatientList" v-if="userStore.hasPermission('patient:read')">
                  <el-icon><User /></el-icon>患者管理
                </el-button>
                <el-button type="primary" @click="toAppointment" v-if="userStore.hasPermission('appointment:read')">
                  <el-icon><Calendar /></el-icon>预约管理
                </el-button>
                <el-button type="primary" @click="toMedicalRecord" v-if="userStore.hasPermission('medical_record:read')">
                  <el-icon><Document /></el-icon>医疗记录
                </el-button>
                <el-button type="primary" @click="toStatistics" v-if="userStore.hasPermission('statistics:read')">
                  <el-icon><DataAnalysis /></el-icon>统计报表
                </el-button>
              </div>
            </div>
            <div class="welcome-image">
              <!-- 移除空图片引用，避免加载错误 -->
              <el-icon class="welcome-icon"><Monitor /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 数据卡片行 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-if="userStore.hasPermission('statistics:read')">
        <el-card class="data-card" shadow="hover">
          <div class="data-header">
            <div class="data-title">今日就诊</div>
            <el-icon class="data-icon"><User /></el-icon>
          </div>
          <div class="data-number">{{ dashboardData.todayVisits }}</div>
          <div class="data-footer">
            <div class="data-trend">
              <span :class="{'trend-up': dashboardData.visitsTrend > 0, 'trend-down': dashboardData.visitsTrend < 0}">
                <el-icon v-if="dashboardData.visitsTrend > 0"><ArrowUp /></el-icon>
                <el-icon v-else-if="dashboardData.visitsTrend < 0"><ArrowDown /></el-icon>
                {{ Math.abs(dashboardData.visitsTrend) }}%
              </span>
              较昨日
            </div>
            <div class="data-total">总数: {{ dashboardData.totalVisits }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-if="userStore.hasPermission('statistics:read')">
        <el-card class="data-card" shadow="hover">
          <div class="data-header">
            <div class="data-title">今日挂号</div>
            <el-icon class="data-icon"><Ticket /></el-icon>
          </div>
          <div class="data-number">{{ dashboardData.todayRegistrations }}</div>
          <div class="data-footer">
            <div class="data-trend">
              <span :class="{'trend-up': dashboardData.registrationsTrend > 0, 'trend-down': dashboardData.registrationsTrend < 0}">
                <el-icon v-if="dashboardData.registrationsTrend > 0"><ArrowUp /></el-icon>
                <el-icon v-else-if="dashboardData.registrationsTrend < 0"><ArrowDown /></el-icon>
                {{ Math.abs(dashboardData.registrationsTrend) }}%
              </span>
              较昨日
            </div>
            <div class="data-total">总数: {{ dashboardData.totalRegistrations }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-if="userStore.hasPermission('statistics:read')">
        <el-card class="data-card" shadow="hover">
          <div class="data-header">
            <div class="data-title">门诊收入</div>
            <el-icon class="data-icon"><Money /></el-icon>
          </div>
          <div class="data-number">¥{{ dashboardData.todayIncome.toLocaleString() }}</div>
          <div class="data-footer">
            <div class="data-trend">
              <span :class="{'trend-up': dashboardData.incomeTrend > 0, 'trend-down': dashboardData.incomeTrend < 0}">
                <el-icon v-if="dashboardData.incomeTrend > 0"><ArrowUp /></el-icon>
                <el-icon v-else-if="dashboardData.incomeTrend < 0"><ArrowDown /></el-icon>
                {{ Math.abs(dashboardData.incomeTrend) }}%
              </span>
              较昨日
            </div>
            <div class="data-total">总数: ¥{{ dashboardData.totalIncome.toLocaleString() }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-if="userStore.hasPermission('statistics:read')">
        <el-card class="data-card" shadow="hover">
          <div class="data-header">
            <div class="data-title">药品库存</div>
            <el-icon class="data-icon"><FirstAidKit /></el-icon>
          </div>
          <div class="data-number">{{ dashboardData.drugInventory }}</div>
          <div class="data-footer">
            <div class="data-alert" v-if="dashboardData.lowStockCount > 0">
              <el-icon><Warning /></el-icon>
              {{ dashboardData.lowStockCount }} 种药品库存不足
            </div>
            <div class="data-alert" v-else>
              <el-icon><SuccessFilled /></el-icon>
              库存充足
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row">
      <!-- 就诊统计图表 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="userStore.hasPermission('statistics:read')">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <div class="chart-title">近期就诊趋势</div>
              <el-radio-group v-model="visitChartType" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="visitChartRef"></div>
        </el-card>
      </el-col>
      
      <!-- 收入统计图表 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="userStore.hasPermission('statistics:read')">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <div class="chart-title">收入分析</div>
              <el-radio-group v-model="incomeChartType" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="incomeChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="table-row">
      <!-- 待办事项 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="todo-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="card-title">待办事项</div>
              <el-button type="primary" size="small" plain>查看全部</el-button>
            </div>
          </template>
          
          <el-empty 
            v-if="!todoList || todoList.length === 0" 
            description="暂无待办事项"
          ></el-empty>
          
          <el-scrollbar height="350px" v-else>
            <div class="todo-list">
              <div 
                v-for="todo in todoList" 
                :key="todo.id" 
                class="todo-item"
                :class="{ 'todo-item-urgent': todo.priority === 'high' }"
              >
                <div class="todo-info">
                  <div class="todo-title">{{ todo.title }}</div>
                  <div class="todo-desc">{{ todo.description }}</div>
                  <div class="todo-time">
                    <el-icon><Timer /></el-icon>
                    {{ todo.deadline }}
                  </div>
                </div>
                <div class="todo-actions">
                  <el-button type="primary" link @click="handleTodo(todo.id)" title="处理">
                    <el-icon><Right /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
      
      <!-- 今日预约 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="userStore.hasPermission('appointment:read')">
        <el-card class="appointment-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="card-title">今日预约</div>
              <el-button type="primary" size="small" plain @click="toAppointment">查看全部</el-button>
            </div>
          </template>
          
          <el-empty 
            v-if="!todayAppointments || todayAppointments.length === 0" 
            description="暂无预约"
          ></el-empty>
          
          <el-scrollbar height="350px" v-else>
            <div class="appointment-list">
              <div 
                v-for="appointment in todayAppointments" 
                :key="appointment.id" 
                class="appointment-item"
              >
                <div class="appointment-time">{{ appointment.time }}</div>
                <div class="appointment-info">
                  <div class="appointment-patient">
                    <el-icon><User /></el-icon>
                    {{ appointment.patientName }}
                  </div>
                  <div class="appointment-doctor">
                    <el-icon><UserFilled /></el-icon>
                    {{ appointment.doctorName }}
                  </div>
                  <div class="appointment-dept">
                    <el-icon><OfficeBuilding /></el-icon>
                    {{ appointment.department }}
                  </div>
                </div>
                <div class="appointment-status">
                  <el-tag 
                    :type="getAppointmentTagType(appointment.status)" 
                    size="small"
                  >
                    {{ appointment.status }}
                  </el-tag>
                </div>
                <div class="appointment-actions">
                  <el-button type="primary" link @click="handleAppointment(appointment.id)" title="处理">
                    <el-icon><Right /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { statisticsAPI, appointmentAPI } from '@/utils/api'
import { ElMessage } from 'element-plus'

// 注册必须的组件
echarts.use([
  BarChart,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  CanvasRenderer
])

const router = useRouter()
const userStore = useUserStore()

// 图表引用
const visitChartRef = ref(null)
const incomeChartRef = ref(null)
let visitChart = null
let incomeChart = null

// 图表类型
const visitChartType = ref('week')
const incomeChartType = ref('week')

// 当前日期
const currentDate = computed(() => {
  const now = new Date()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  return `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日 ${weekdays[now.getDay()]}`
})

// 仪表盘数据
const dashboardData = reactive({
  todayVisits: 0,
  totalVisits: 0,
  visitsTrend: 0,
  todayRegistrations: 0,
  totalRegistrations: 0,
  registrationsTrend: 0,
  todayIncome: 0,
  totalIncome: 0,
  incomeTrend: 0,
  drugInventory: 0,
  lowStockCount: 0,
  expiringCount: 0
})

// 待办事项列表
const todoList = ref([
  {
    id: 1,
    title: '完成患者预约审核',
    description: '需要审核15位患者的预约申请',
    deadline: '今天 14:00',
    priority: 'high'
  },
  {
    id: 2,
    title: '检查药品库存',
    description: '确认低库存药品并进行补货',
    deadline: '今天 16:30',
    priority: 'medium'
  },
  {
    id: 3,
    title: '更新患者病历',
    description: '更新李明的最新检查结果',
    deadline: '今天 17:00',
    priority: 'normal'
  }
])

// 今日预约列表
const todayAppointments = ref([])

// 获取仪表盘统计数据
const fetchDashboardData = async () => {
  try {
    // 构建查询参数
    const now = new Date()
    const params = {
      date: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
    }
    
    // 这里模拟数据，实际项目中应该从后端API获取
    // 可以替换为实际的API调用
    // const res = await statisticsAPI.getDashboardData(params)
    
    // 模拟数据
    dashboardData.todayVisits = 56
    dashboardData.totalVisits = 1245
    dashboardData.visitsTrend = 12.5
    
    dashboardData.todayRegistrations = 78
    dashboardData.totalRegistrations = 2567
    dashboardData.registrationsTrend = -5.2
    
    dashboardData.todayIncome = 25600
    dashboardData.totalIncome = 1568900
    dashboardData.incomeTrend = 8.3
    
    dashboardData.drugInventory = 1658
    dashboardData.lowStockCount = 5
    dashboardData.expiringCount = 12
    
    // 初始化图表
    initCharts()
  } catch (error) {
    console.error('获取仪表盘数据失败', error)
  }
}

// 获取今日预约
const fetchTodayAppointments = async () => {
  try {
    // 构建查询参数
    const now = new Date()
    const params = {
      date: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
      limit: 10
    }
    
    // 这里模拟数据，实际项目中应该从后端API获取
    // const res = await appointmentAPI.getAppointments(params)
    
    // 模拟数据
    todayAppointments.value = [
      {
        id: 1,
        time: '09:00-09:30',
        patientName: '张三',
        doctorName: '李医生',
        department: '内科',
        status: '待就诊'
      },
      {
        id: 2,
        time: '10:00-10:30',
        patientName: '李四',
        doctorName: '王医生',
        department: '外科',
        status: '已到诊'
      },
      {
        id: 3,
        time: '11:00-11:30',
        patientName: '王五',
        doctorName: '赵医生',
        department: '儿科',
        status: '已取消'
      },
      {
        id: 4,
        time: '14:00-14:30',
        patientName: '赵六',
        doctorName: '钱医生',
        department: '妇科',
        status: '待就诊'
      },
      {
        id: 5,
        time: '15:00-15:30',
        patientName: '孙七',
        doctorName: '周医生',
        department: '骨科',
        status: '已完成'
      }
    ]
  } catch (error) {
    console.error('获取今日预约失败', error)
  }
}

// 初始化图表
const initCharts = () => {
  // 销毁之前的图表实例
  if (visitChart) {
    visitChart.dispose()
  }
  if (incomeChart) {
    incomeChart.dispose()
  }
  
  // 初始化就诊趋势图表
  visitChart = echarts.init(visitChartRef.value)
  const visitOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['门诊量', '住院量'],
      right: 10,
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: visitChartType.value === 'week' 
        ? ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        : Array.from({length: 30}, (_, i) => i + 1)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '门诊量',
        type: 'bar',
        stack: 'total',
        barWidth: '40%',
        color: '#409EFF',
        data: visitChartType.value === 'week'
          ? [45, 52, 49, 56, 63, 35, 28]
          : Array.from({length: 30}, () => Math.floor(Math.random() * 40) + 30)
      },
      {
        name: '住院量',
        type: 'bar',
        stack: 'total',
        barWidth: '40%',
        color: '#67C23A',
        data: visitChartType.value === 'week'
          ? [23, 25, 27, 22, 24, 18, 15]
          : Array.from({length: 30}, () => Math.floor(Math.random() * 20) + 15)
      }
    ]
  }
  visitChart.setOption(visitOption)
  
  // 初始化收入分析图表
  incomeChart = echarts.init(incomeChartRef.value)
  const incomeOption = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['门诊收入', '住院收入', '药房收入'],
      right: 10,
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: incomeChartType.value === 'week' 
        ? ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        : Array.from({length: 30}, (_, i) => i + 1)
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 元'
      }
    },
    series: [
      {
        name: '门诊收入',
        type: 'line',
        smooth: true,
        color: '#409EFF',
        data: incomeChartType.value === 'week'
          ? [12500, 13600, 14200, 15800, 16200, 9800, 8500]
          : Array.from({length: 30}, () => Math.floor(Math.random() * 10000) + 8000)
      },
      {
        name: '住院收入',
        type: 'line',
        smooth: true,
        color: '#67C23A',
        data: incomeChartType.value === 'week'
          ? [28500, 29700, 31200, 32500, 33100, 25400, 24800]
          : Array.from({length: 30}, () => Math.floor(Math.random() * 15000) + 20000)
      },
      {
        name: '药房收入',
        type: 'line',
        smooth: true,
        color: '#E6A23C',
        data: incomeChartType.value === 'week'
          ? [8500, 9200, 8700, 9500, 10200, 6500, 5800]
          : Array.from({length: 30}, () => Math.floor(Math.random() * 5000) + 5000)
      }
    ]
  }
  incomeChart.setOption(incomeOption)
}

// 监听图表类型变化
watch(visitChartType, () => {
  initCharts()
})

watch(incomeChartType, () => {
  initCharts()
})

// 处理窗口大小变化，重绘图表
const resizeCharts = () => {
  visitChart && visitChart.resize()
  incomeChart && incomeChart.resize()
}

// 获取预约状态标签类型
const getAppointmentTagType = (status) => {
  switch (status) {
    case '待就诊':
      return 'warning'
    case '已到诊':
      return 'success'
    case '已完成':
      return 'info'
    case '已取消':
      return 'danger'
    default:
      return 'info'
  }
}

// 处理待办事项
const handleTodo = (id) => {
  console.log('处理待办事项:', id)
}

// 处理预约
const handleAppointment = (id) => {
  router.push(`/appointments/detail/${id}`)
}

// 导航到不同页面
const toPatientList = () => {
  try {
  router.push('/patients/list')
  } catch (error) {
    console.error('导航到患者列表失败:', error)
    ElMessage.warning('无法导航到患者列表页面')
  }
}

const toAppointment = () => {
  try {
  router.push('/appointments/list')
  } catch (error) {
    console.error('导航到预约管理失败:', error)
    ElMessage.warning('无法导航到预约管理页面')
  }
}

const toMedicalRecord = () => {
  try {
  router.push('/medical-records/list')
  } catch (error) {
    console.error('导航到医疗记录失败:', error)
    ElMessage.warning('无法导航到医疗记录页面')
  }
}

const toStatistics = () => {
  try {
  router.push('/statistics/overview')
  } catch (error) {
    console.error('导航到统计页面失败:', error)
    ElMessage.warning('无法导航到统计页面')
  }
}

// 当页面加载完成时，输出当前用户角色信息
onMounted(() => {
  fetchDashboardData()
  fetchTodayAppointments()
  window.addEventListener('resize', resizeCharts)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)
  if (visitChart) {
    visitChart.dispose()
    visitChart = null
  }
  if (incomeChart) {
    incomeChart.dispose()
    incomeChart = null
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.welcome-card {
  margin-bottom: 20px;
  background-image: linear-gradient(120deg, #f0f7ff 0%, #ffffff 100%);
}

.welcome-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.welcome-info {
  flex: 1;
}

.welcome-info h2 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.welcome-info p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 20px;
}

.quick-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-top: 20px;
}

.welcome-image {
  margin-left: 20px;
  max-width: 200px;
}

.data-card {
  height: 160px;
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.data-title {
  font-size: 16px;
  color: #909399;
}

.data-icon {
  font-size: 20px;
  color: #409EFF;
}

.data-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  line-height: 1;
}

.data-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.data-trend {
  display: flex;
  align-items: center;
  color: #909399;
}

.trend-up {
  color: #67C23A;
  margin-right: 5px;
  display: flex;
  align-items: center;
}

.trend-down {
  color: #F56C6C;
  margin-right: 5px;
  display: flex;
  align-items: center;
}

.data-total {
  color: #909399;
}

.data-alert {
  display: flex;
  align-items: center;
  color: #E6A23C;
  font-size: 14px;
}

.data-alert .el-icon {
  margin-right: 5px;
}

.chart-row {
  margin-bottom: 30px;
}

.chart-card {
  margin-bottom: 30px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 350px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.todo-list, .appointment-list {
  display: flex;
  flex-direction: column;
}

.todo-item, .appointment-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #EBEEF5;
  align-items: center;
}

.todo-item:last-child, .appointment-item:last-child {
  border-bottom: none;
}

.todo-item-urgent {
  position: relative;
}

.todo-item-urgent::before {
  content: '';
  position: absolute;
  left: -8px;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #F56C6C;
  border-radius: 1px;
}

.todo-info, .appointment-info {
  flex: 1;
}

.todo-title, .appointment-patient {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.todo-desc {
  font-size: 13px;
  color: #606266;
  margin-bottom: 5px;
}

.todo-time, .appointment-doctor, .appointment-dept {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  margin-bottom: 3px;
}

.todo-time .el-icon, .appointment-doctor .el-icon, .appointment-dept .el-icon {
  margin-right: 5px;
}

.todo-actions, .appointment-actions {
  margin-left: 10px;
}

.appointment-time {
  width: 100px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.appointment-status {
  margin: 0 15px;
}

@media screen and (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
  }
  
  .welcome-image {
    margin-left: 0;
    margin-top: 20px;
  }
  
  .data-card {
    height: auto;
    margin-bottom: 15px;
  }
  
  .chart-container {
    height: 250px;
  }

  /* 添加移动端适配 */
  .dashboard-container {
    padding: 10px;
  }
}
</style> 